<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>确认订单-{{$SEO['title']}}</title>
    <meta name="keywords" content="{{$SEO['keywords']}}"/>
    <meta name="description" content="{{$SEO['description']}}"/>

    <!--公用css引用-->
    @include('front.common.style')
    <!--END/公用css引用-->
    {{--<link rel="stylesheet" href="{{asset('/css/index.css')}}">--}}
    <link rel="stylesheet" href="../dist/css/confirm-order.css">
</head>
<body>

<!--公共头部-->
@include('front.common.header', ['noTopNav' => 'true'])
<!--END/公共头部-->

@inject('cartService','App\Interfaces\CartService')

@inject('pictureService','App\Interfaces\PictureService')

@inject('discountService','App\Interfaces\DiscountService')


<!--订单确认信息-->
<div class="inbox add-order">
    <div class="ad-o-h">
        <span class="h-txt">填写并核对订单信息</span>
    </div>
    <form action="" class="js-form">

    <div class="ad-o-b">
        <div class="ad-o-inner">
            <div class="o-b-h1 fn-ohide">
                <span class="h-txt">收货人信息</span>
                <a href="my/address" target="_blank" class="js-add more">管理收货地址</a>
            </div>

            <div class="o-b-b order-address">
                <ul class="js-selAddress address">
                    <?php $address_id ='' ?>

                    @foreach($address as $k=>$addressItem)
                    <?php
                        $is_default = $addressItem->is_default;
                        $address_id = $is_default==true||$address_id==''?$addressItem->address_id:$address_id;
                    ?>
                    <li data-id="{{$addressItem->address_id}}">
                        <div class="tag-st fn-dib @if($is_default) cur @endif ">
                            <span class="tag-txt fn-dib-otw" title="{{$addressItem->consignee}}">{{$addressItem->consignee}}</span>
                            <span class="tag-txt fn-dib-otw" title="{{$addressItem->city}}">{{$addressItem->city}}</span>
                            <img class="rd" src="../images/right.png" alt="" >
                        </div>

                        <div class="info fn-dib">
                            <span class="fn-dib fn-dib-otw name" title="{{$addressItem->consignee}}">{{$addressItem->consignee}}</span>
                            <span class="fn-dib fn-dib-otw pos" title="{{$addressItem->province}} {{$addressItem->city}} {{$addressItem->district}} {{$addressItem->address}}">{{$addressItem->province}} {{$addressItem->city}} {{$addressItem->district}} {{$addressItem->address}}</span>
                            <span class="fn-dib fn-dib-otw tel">{{$addressItem->mobile}}</span>
                        </div>
                    </li>
                    @endforeach
                    <li class="order-address-add">
                        <div class="ajax-add-more add-btn-wrap">
                            <a href="javascript:;" class="js-addMore fn-btn fn-mr10">新增收货地址</a>
                            <span class="text-color-7">最多可创建<span class="total">20</span>个收货地址。</span>
                        </div>
                    </li>
                </ul>
                <input id="address_id" type="hidden" name="address_id" value="{{$address_id}}"/>
            </div>

        </div>


        <!--配送方式-->
        <div class="ad-o-inner ad-o-hor fn-ohide">
            <div class="o-b-h1">
                <span class="h-txt">配送方式</span>
            </div>
            <div class="o-b-fl">
                <div class="text-color-1">快递配送</div>
                <input type="hidden" name="expressType" value="sto">
            </div>
        </div>
        <!--END/配送方式-->


        <div class="ad-o-inner fn-ohide">
            <div class="o-b-h1">
                <span class="h-txt">确认商品信息</span>
                <a href="/cart" class=" more">返回购物车 &gt;</a>
            </div>
            <?php
            $hasEShopGoods=false;
            $hasCShopGoods=false;
            ?>

            @if($info['total_buy_number']>0)
                @foreach($info['orders'] as $key=>$order)
                    @if($key == 'cshopGoods' && $order['caculator']['total_number']>0)
                        <?php $hasCShopGoods=true; ?>
                        <div class="o-b-b fn-mt10">
                            <div class="tit">
                                <div class="h">免税商品</div>
                            </div>
                            <table id="cshopOrder" class="bl-table bl-table-brdli o-g-list table-tc">
                                <tr>
                                    <td colspan="2" class="tl">商品详情</td>
                                    <td>单价</td>
                                    <td>折扣价</td>
                                    <td>优惠金额</td>
                                    <td>数量</td>
                                    <td class="yf">关税</td>
                                </tr>

                                @foreach($order['orderGoods'] as $index=>$goods)
                                    <tr data-id="{{$goods['goods_id']}}">
                                        <td class="pic tl">
                                            <a href="/goods/{{$goods['goods_id']}}" target="_blank" title="{{$goods['goods_name']}}">
                                                <img class="goods-img" src="{{$pictureService::thumb($goods['goods_thumb'], 70, 70)}}" alt="{{$goods['goods_name']}}">
                                            </a>
                                        </td>
                                        <td class="tl name">
                                            <p class="name"><a class="link" href="/goods/{{$goods['goods_id']}}" target="_blank" title="{{$goods['goods_name']}}">{{$goods['goods_name']}}</a></p>
                                        </td>

                                        <td>
                                            <span>￥{{number_format($goods['shop_price'],2)}}</span>
                                        </td>
                                        <td>
                                            <span>￥{{$goods['goods_real_price']}}</span>
                                        </td>
                                        <td>
                                            <span>-{{sprintf("%.2f",substr(sprintf("%.3f", $goods['shop_price'] - $goods['goods_real_price']), 0, -1))}}</span>
                                        </td>
                                        <td>
                                            <span>{{$info['buyGoods'][$goods['goods_id']]}}</span>
                                        </td>
                                        <td>
                                            <span class="text-color-1">0.00</span>
                                        </td>
                                    </tr>
                                @endforeach

                                <tr>
                                    <td class="tr bg-4" colspan="7">
                                        <span class="fn-mr20">本单商品总数：{{$order['caculator']['total_number']}}</span>
                                        <span class="js-totalPrice fn-mr20">本单总价：￥{{number_format($order['caculator']['pay_price'],2,'.','')}}</span>
                                        <span class="js-orderShippingFee fn-ml20">本单运费：￥<span class="js-num">{{number_format($order['caculator']['shipping_fee'],2)}}</span></span>

                                        <div class="fn-dib hover-show-tip fn-rel">
                                            <i class="icon icon-tip icon-tip-3 fn-ml4" style="margin-top: -4px;"></i>
                                            <div class="bl-tip-box tip-skin-gray fn-tl" style="left: -226px;top:26px;right: auto;">
                                                <div class="J-box TJ-box" style="left: 232px;"><span class="J"></span><i class="J"></i></div>
                                                <div class="mask-T"></div>
                                                <div class="bl-tip-con" style="width: 220px;">
                                                    <p>免税商品全场满59包邮。</p>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    @elseif($key == 'eshopGoods' && $order['caculator']['total_number']>0)
                        <?php $hasEShopGoods=true; ?>
                        <div class="o-b-b fn-mt10">
                            <div class="tit">
                                <div class="h">E贸易商品</div>
                            </div>
                            <table id="eshopOrder" class="bl-table bl-table-brdli o-g-list table-tc">
                                <tr>
                                    <td colspan="2" class="tl">商品详情</td>
                                    <td>单价</td>
                                    <td>折扣价</td>
                                    <td>优惠金额</td>
                                    <td>数量</td>
                                    <td class="yf">关税</td>
                                </tr>

                                @foreach($order['orderGoods'] as $index=>$goods)
                                    <?php

                                        $tariffPercent= ($goods['excise_duty_percent']+$goods['value_added_tax_percent'])*0.7;

                                        // $tariff = $info['buyGoods'][$goods['goods_id']]*$goods['shop_price']*$tariffPercent/100;
                                        // $tariff = $info['buyGoods'][$goods['goods_id']]*$goods['goods_real_price']*$tariffPercent/100;

                                        /*$excise_duty_percent = intval(empty($goods['recode_excise_duty_percent']) ? $goods['excise_duty_percent'] : $goods['recode_excise_duty_percent']);//消费税

                                        $value_added_tax_percent = intval(empty($goods['recode_value_added_tax_percent']) ? $goods['value_added_tax_percent'] : $goods['recode_value_added_tax_percent']);//增值税*/

                                        if ($goods['recode_excise_duty_percent'] == 0) {

                                            $excise_duty_percent = 0;
                                        }elseif ($goods['recode_excise_duty_percent'] > 0) {

                                            $excise_duty_percent = $goods['recode_excise_duty_percent'];
                                        }elseif ($goods['recode_excise_duty_percent'] < 0) {

                                            $excise_duty_percent = $goods['excise_duty_percent'];
                                        }else{

                                            $excise_duty_percent = $goods['excise_duty_percent'];
                                        }


                                        $excise_tax = 0.00;

                                        if ($excise_duty_percent) {
                                            /**
                                             * 消费税=（完税价格+关税）/（1-消费税率）*消费税率*70%=1/(1-0.15）*0.15*0.7=0.123529
                                             * 增值税=（完税价格+关税+消费税）*0.17*0.7=（1+0+0.17647）*0.17*0.7=0.13999
                                             * （注：完税价格为固定值1，关税为固定值0）
                                             *
                                             * 含消费税的综合税率=消费税+增值税=0.123529+0.13999=0.263519=0.2635
                                             * 不含消费税的综合税率=0.119
                                             *
                                             * 注：计算增值税时，消费税要全额计算，不是0.7之后的消费税
                                             *
                                             * 商品的综合税率 = 消费税 + 增值税；
                                             * 商品的税金 = 商品价格 * 商品数量 * 综合税率。（订单中产生的关税）
                                             */
                                            $excise_tax = 1 / (1 - $excise_duty_percent / 100) * $excise_duty_percent / 100 * 70 / 100;                 //消费税
                                        }

                                        $value_added_tax = (1 + 0 + $excise_tax * 100 / 70) * 17 / 100 * 70 / 100;         //增值税

                                        $consolidated_tax = $excise_tax + $value_added_tax;

                                        $tariff = $info['buyGoods'][$goods['goods_id']]*$goods['goods_real_price'] * $consolidated_tax;
                                    ?>
                                    <tr data-id="{{$goods['goods_id']}}">
                                        <td class="pic tl">
                                            <a href="/goods/{{$goods['goods_id']}}" target="_blank" title="{{$goods['goods_name']}}">
                                                <img class="goods-img" src="{{$pictureService::thumb($goods['goods_thumb'], 70, 70)}}" alt="{{$goods['goods_name']}}">
                                            </a>
                                        </td>
                                        <td class="tl name">
                                            <p class="name"><a class="link" href="/goods/{{$goods['goods_id']}}" target="_blank" title="{{$goods['goods_name']}}">{{$goods['goods_name']}}</a></p>
                                        </td>

                                        <td>
                                            <span>￥{{number_format($goods['shop_price'],2)}}</span>
                                        </td>
                                        <td>



                                            <span>￥{{$goods['goods_real_price']}}</span>
                                        </td>
                                        <td>
                                            <span>-{{sprintf("%.2f",substr(sprintf("%.3f", $goods['shop_price'] - $goods['goods_real_price']), 0, -1))}}</span>
                                        </td>
                                        <td>
                                            <span>{{$info['buyGoods'][$goods['goods_id']]}}</span>
                                        </td>
                                        <td>
                                            <span class="text-color-1">{{number_format($tariff,2)}}</span>
                                        </td>
                                    </tr>
                                @endforeach

                                <tr>
                                    <td class="tr bg-4" colspan="7">
                                        <span class="fn-mr20">本单商品总数：{{$order['caculator']['total_number']}}</span>
                                        <span class="js-totalPrice fn-mr20">本单总价：￥{{number_format($order['caculator']['pay_price'],2)}}</span>

                                        @if($order['caculator']['total_tariff_fee']>50)
                                            <span>本单关税：￥{{number_format($order['caculator']['total_tariff_fee'],2)}}</span>
                                        @endif

                                        <span class="js-orderShippingFee @if(!$default_address_id) fn-hide @endif fn-ml20">本单运费：￥<span class="js-num">{{number_format($order['caculator']['shipping_fee'],2)}}</span></span>


                                        <div class="fn-dib hover-show-tip fn-rel">
                                            <i class="icon icon-tip icon-tip-3 fn-ml4" style="margin-top: -4px;"></i>
                                            <div class="bl-tip-box tip-skin-gray fn-tl" style="left: -226px;top:26px;right: auto;">
                                                <div class="J-box TJ-box" style="left: 232px;"><span class="J"></span><i class="J"></i></div>
                                                <div class="mask-T"></div>
                                                <div class="bl-tip-con" style="width: 220px;">
                                                    <p>E贸易商品全场包邮。</p>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    @endif

                @endforeach
            @endif

            <!--优惠券-->
            <div class="ad-o-inner ad-o-hor fn-ohide fn-mt20">
                <div class="o-b-h1" style="width: 60px;">

                    <span class="h-txt">优惠券</span>
                </div>
                <div class="o-b-fl">

                    @if (@count($info['orders']['eshopGoods']['coupons'])>0 || count($info['orders']['cshopGoods']['coupons'])>0)
                    <div class="ui-cols-2">
                        <div class="col">
                            <dl class="fn-ml20">
                                <dt class="bg-4"><span class="fn-ml20">E贸易商品订单优惠券(限用一张)</span></dt>
                                @if($hasEShopGoods && count($info['orders']['eshopGoods']['coupons'])>0)
                                <?php $user_coupons = $info['orders']['eshopGoods']['coupons']; ?>
                                    @foreach($user_coupons as $available_key=>$available_value)
                                        <dd class="fn-ml20">
                                            <label>
                                                <input class="J-couponSelE" value="{{$available_value['id']}}" type="checkbox" name="e_coupon_id">
                                                <?php
                                                    switch ($available_value['type']) {
                                                        case '1':
                                                            echo '全场通用券';
                                                            break;
                                                        case '2':
                                                            echo '商品优惠券';
                                                            break;
                                                        case '3':
                                                            echo '分类优惠券';
                                                            break;
                                                        case '4':
                                                            echo '店铺优惠券';
                                                            break;
                                                        case '5':
                                                            echo '品牌优惠券';
                                                            break;
                                                    }
                                                    //end switch()
                                                ?>:&nbsp;&nbsp;满{{$available_value['limit_fir']}}减{{$available_value['value']}}元
                                            </label>
                                        </dd>

                                    @endforeach
                                @endif
                            </dl>
                        </div>
                        <div class="col">
                            <dl class="fn-ml20">
                                <dt class="bg-4"><span class="fn-ml20">普通商品订单优惠券(限用一张)</span></dt>
                                @if($hasCShopGoods && count($info['orders']['cshopGoods']['coupons'])>0)
                                <?php $user_coupons = $info['orders']['cshopGoods']['coupons'];?>
                                    @foreach($user_coupons as $available_key=>$available_value)
                                        <dd class="fn-ml20">
                                            <label>
                                                <input class="J-couponSelC" value="{{$available_value['id']}}" type="checkbox" name="c_coupon_id">
                                                <?php
                                                switch ($available_value['type']) {
                                                    case '1':
                                                        echo '全场通用券';
                                                        break;
                                                    case '2':
                                                        echo '商品优惠券';
                                                        break;
                                                    case '3':
                                                        echo '分类优惠券';
                                                        break;
                                                    case '4':
                                                        echo '店铺优惠券';
                                                        break;
                                                    case '5':
                                                        echo '品牌优惠券';
                                                        break;
                                                }
                                                //end switch()
                                                ?>:&nbsp;&nbsp;满{{$available_value['limit_fir']}}减{{$available_value['value']}}元
                                            </label>
                                        </dd>

                                    @endforeach
                                @endif
                            </dl>
                        </div>
                    </div>
                    @else
                    <div class="fn-ml20">无可用优惠券</div>
                    @endif
                </div>
            </div>
            <!--END/优惠券-->




                        <div class="o-b-b">
                <div class="o-sel-sub fn-tr">
                    <p>
                        <span class="label">商品件数：</span>
                        <span class="fn-dib val">{{$info['total_buy_number']}}件</span>
                    </p>

                    <p>
                        <span class="label">金额合计：</span>
                        <span class="js-totalOrderPrice fn-dib val">￥{{number_format($info['total_order_price'],2,'.','')}}</span>
                    </p>

                    <p>
                        <span class="label">关税：</span>
                        <span class="fn-dib val">￥{{number_format($info['total_tariff_fee'],2,'.','')}}</span>
                    </p>

                    <p class="js-totalShippingFee">
                        <span class="label">运费：</span>
                        <span class="fn-dib val">￥<span class="js-num">{{number_format($info['total_shipping_fee'],2)}}</span></span>
                    </p>

                    <p class="J-couponNum fn-hide-">
                        <span class="label">优惠券：</span>
                        <span class="fn-dib val">-￥<span class="J-val">0.00</span></span>
                    </p>

                    <p class="J-discountNum fn-hide-">
                        <span class="label">限时折扣：</span>
                        <span class="fn-dib val">-￥<span class="J-val">{{number_format($info['total_discount_price'],2)}}</span></span>
                    </p>

                    <p class="total-num">
                        <span class="label">应付金额：</span>
                        <span class="js-totalPayPrice fn-dib val">￥{{number_format($info['total_pay_price'],2,'.','')}}</span>
                    </p>
                </div>
            </div>
        </div>

        <div class="ad-btn-wrap">
            <span>注：由于仓储不同，免税商品和E贸易商品将拆分成两个订单，需要单独进行支付。</span>
            <input type="hidden" name="payType" value="alipay">
            <a id="J_create_order" href="javascript:;" class="fn-btn btn-primary pay-btn">提交订单</a>
        </div>


    </div>

    </form>
</div>

<!--公共尾部-->
@include('front.common.footer')
<!--END/公共尾部-->

<!--公用js引用-->
@include('front.common.script')
<!--END/公用js引用-->

<script id="formTpl" type="text/html">
    <form method="GET" action="/my/address/create" class="form-horizontal js-form bl-form bl-formhor form-L fn-mt20 fn-mb20">
        <ul class="ul-group ajax-form">

            <li class="fn-hide">
                <input name="country" type="text" value="中国">
            </li>

            <li class="bl-form-group">
                <label><em class="text-color-6">*</em>所在地区：</label>
                <div class="controls">
                    <div class="select2-container fn-dib selectinput fn-mt6">
                        <select id="area" class="elementJs"></select>
                        <img src="../images/loading-1.gif" alt="" class="js-loading form-help fn-mt6">
                    </div>
                    <input type="text" class="js-areaInput fn-vhide fn-vl" name="position_ids" required data-msg-required="请选择">
                    <div class="fn-hide js-areaName">
                        <input type="text" name="province">
                        <input type="text" name="city">
                        <input type="text" name="district">
                    </div>
                </div>
            </li>

            <li class="bl-form-group">
                <label class="col-sm-8 control-label"><em class="text-color-6">*</em>详细地址：</label>
                <div class='col-sm-3 controls'>
                    <input id="detailAddress" class="form-control fn-tinput fn-tinput-longer elementJs" type="text" name="address" placeholder="无需重复填写省市区，小于75个字" required data-msg-required="请填写详细地址" maxlength="75" data-msg-maxlength="小于75个字">
                </div>
            </li>

            <li class="bl-form-group">
                <label><em class="text-color-6">*</em>收货人名称：</label>
                <div class="controls">
                    <input id="consignee" class="form-control fn-tinput fn-tinput-longer elementJs" type="text" name="consignee" placeholder="请使用真实姓名，长度不超过12个字" required data-msg-required="请填写收货人" maxlength="75" data-msg-maxlength="小于12个字">
                </div>
            </li>

            <li class="bl-form-group">
                <label><em class="text-color-6">*</em>身份证号码：</label>
                <div class="controls">
                    <input id="id_card" class="form-control fn-tinput fn-tinput-longer elementJs" type="text" name="id_card" placeholder="请填写收货人本人的真实身份证号码" required data-msg-required="请填写身份证" data-rule-idCard="true">
                </div>
            </li>

            <li class="bl-form-group">
                <label><em class="text-color-6">*</em>手机号码：</label>
                <div class="controls">
                    <input id="mobile" class="form-control fn-tinput fn-tinput-longer elementJs" type="text" name="mobile" placeholder="请填写常用手机号" required data-msg-required="请填写手机号" data-rule-mobile="true">
                </div>
            </li>

            <li class="bl-form-group bl-form-btns">
                <label class="fn-vhide">提交：</label>
                <div class="controls">
                    <button class="fn-btn btn-primary fn-mr8 btn-save" type="submit">保存收货地址</button>
                    <button class="fn-btn btn-nostyle btn-cancel" type="button">取消</button>
                    <label><input type="checkbox" name="is_default" value="1">设为默认地址</label>
                </div>
            </li>
        </ul>
    </form>
</script>

<script id="listTpl" type="text/html">
    <li data-id="${address_id}">
        <div class="tag-st fn-dib" data-isDef="${is_default}">
            <span class="tag-txt fn-dib-otw">${consignee}</span>
            <span class="tag-txt fn-dib-otw">${city}</span>
            <img class="rd" src="../images/right.png" alt="" >
        </div>

        <div class="info fn-dib">
            <span class="fn-dib fn-dib-otw name">${consignee}</span>
            <span class="fn-dib fn-dib-otw pos">${province} ${city} ${district} ${address}</span>
            <span class="fn-dib fn-dib-otw tel">${mobile}</span>
        </div>
    </li>
</script>
<script src="../dist/js/linkagesel/linkagesel-min.js"></script>
<script src="../dist/js/jquery.validation.js"></script>
<script>
    $(function(){
        //地址
        var selAddress=$('.js-selAddress');
        var formTpl=$('#formTpl').html(),
            listTpl=$('#listTpl').html();
        var linkageSel,addressId='';

        var curAdd=selAddress.find('li').has('.tag-st.cur');

        addressId=curAdd.length?curAdd.data('id'):'';

        selAddress.on('click','.tag-st',function(){
            var that=$(this),
                liItem=that.closest('li'),
                prevCur=selAddress.find('.tag-st.cur'),
                addressInput=selAddress.next('input');

            var addressId=liItem.data('id');
            addressInput.val(addressId);
            prevCur.removeClass('cur');
            that.addClass('cur');

            //获取运费信息
            updatePrice({
                addressId:addressId,
                e_coupon_id:e_coupon_id,
                c_coupon_id:c_coupon_id,
                cb: function(){}
            });

        });

        //添加地址
        selAddress.on('click','.js-addMore',function(){
            var addBtn=$(this);

            //弹出窗口
            layer.open({
                title:'添加收货地址',
                type: 1,
                skin: 'layui-layer-rim', //加上边框
                area: ['640px','400px'], //宽高
                content: formTpl,
                success: function(layero, index){//layero--当前层DOM,index--当前层索引

                    //地区选择实例化
                    var jsForm=$('.js-form',layero),
                        areaInput = $('.js-areaInput',layero),
                        areaNameInputs=$('.js-areaName',layero).find('input');

                    linkageSel=getAreaData('',function(linkAge){
                        var d = linkAge.getSelectedDataArr('name'),    // 所有有选定菜单的name. this === linkageSel2
                            idArr = linkAge.getSelectedArr(),
                            arr = [];

                        for (var i = 0, len = d.length; i < len; i++) {
                            arr.push(d[i]);
                        }

                        if(d.length==3){
                            areaInput.siblings('label.error').remove();
                            areaInput.val(idArr);
                            areaInput.data('text', d.join(' '));
                        }else{
                            areaInput.val('');
                            areaInput.data('text', '');
                        }


                        for(var j=0;j<areaNameInputs.length;j++){
                            areaNameInputs.eq(j).val(d[j]).trigger('input change');
                        }
                    },$('.js-loading',layero));

                    //表单验证
                    jsForm.validate({
                        submitHandler:function(form){
                            var btn=jsForm.find('.btn-save');

                            btn.addClass('disabled').prop('disabled',true).text('提交中...');
                            tools.log(jsForm.serialize());
                            $.ajax({
                                url:form.action,
                                type:'get',
                                dataType:'json',
                                data:jsForm.serialize(),
                                success:function(res){
                                    if(res.status&&res.address_id){
                                        addressId=res.address_id;
                                        var addressInput= $('#address_id');
                                        //渲染页面并给地址input赋值
                                        var data={},formData=jsForm.serializeArray();
                                        for(var i=0;i<formData.length;i++){
                                            data[formData[i].name]=formData[i].value;
                                        }
                                        data.address_id=res.address_id;

                                        var curLi=$(tools.htmlTemplate(listTpl,data));


                                        //curLi.insertBefore(addBtn.closest('li'));
                                        addBtn.closest('ul').prepend(curLi);
                                        addBtn.closest('ul').scrollTop(0);
                                        addressInput.val(res.address_id);
                                        curLi.find('.tag-st').trigger('click');

//                                        if(data.is_default || addressInput.val()==''){
//                                            addressInput.val(res.address_id);
//                                        }
//                                        if(data.is_default||addBtn.closest('li').siblings('li').length==1){
//                                            curLi.find('.tag-st').trigger('click');
//                                        }
                                        btn.removeClass('disabled').prop('disabled',false).text('新增收货地址');
                                        layer.close(index);//关闭弹层

                                    }
                                },
                                error:function(error){
                                    //渲染错误信息
                                    btn.removeClass('disabled').prop('disabled',false).text('新增收货地址');
                                }
                            });
                        }
                    });

                    //取消事件
                    jsForm.on('click','.btn-cancel',function(){
                       layer.close(index);
                    });
                }
            });
        });

        //收货时间
        $('.js-simRadio').on('click','.js-check',function(){
            var that=$(this),wrap=that.closest('.js-simRadio');

            if(that.hasClass('cur')) return false;

            that.addClass('cur').siblings('.cur').removeClass('cur').find('input').prop('checked',false);
            that.find('input').prop('checked',true);

            //切换发票抬头
            var selTxt=$('.js-selectedTxt',wrap);
            if(selTxt.length){
                selTxt.text(that.find('label').text());
            }

            return false;
        });

        //支付
        $('#J_create_order').click(function(e){

            var btn = $(this);
            if(btn.hasClass('disabled')) return false;


            var form=$('.js-form').serialize();
            btn.addClass('disabled').text('提交中...');

            var url='/order';
            url=url+ '?from={{$from}}';
            url=url+ '&e_coupon_id=' + e_coupon_id + '&c_coupon_id='+c_coupon_id;
// url=url+ '&e_discount_id=3&c_discount_id=5';

            tools.log(url);
// console.log(url);
// debugger;
            $.ajax({
                type:'post',
                dataType:'json',
                url:url,
                data:form,
                success:function(response){
                    tools.log('success',response);
                    if(response.status=='402'){
                        //错误提示
                        btn.removeClass('disabled').text('提交订单');
                    }

                    if (response.status=='success'){
                        window.location.replace('/pay/'+response.order_pay_id);
                    }

                },
                error:function(error){
                    tools.log('error',error);

                    btn.removeClass('disabled').text('提交订单');

                    if (error.status==422){
                        var errors = error.responseJSON;
                        errors.address_id&&layer.alert(errors.address_id[0]);
                        errors.payType&&layer.alert(errors.payType[0]);
                        errors.expressType&&layer.alert(errors.expressType[0]);
                    }

                }
            });

        });


        //优惠券
        var couData={
            e_coupon_id:'',
            c_coupon_id:'',
            e_discount_id:'',
            c_discount_id:''
        };
        var couponNum=$('.J-couponNum');//优惠券
        var discountNum=$('.J-discountNum');//限时折扣
        var couponSelE=$('.J-couponSelE');
        var couponSelC=$('.J-couponSelC');
        var discountSelE=$('.J-discountSelE');
        var discountSelC=$('.J-discountSelC');
        var e_coupon_id='',c_coupon_id='',e_discount_id='',c_discount_id='';

        couponSelE.on('change',function(){
            var that=$(this),isChecked=that.prop('checked');
            var sibs=that.closest('dd').siblings('dd').find('input');

            if(addressId){
                changeCouponStatus(that,sibs,couponSelC,isChecked);
            }else{
                layer.alert('请选择收货地址！');
                that.prop('checked',false);
            }
        });

        couponSelC.on('change',function(){
            var that=$(this),isChecked=that.prop('checked');
            var sibs=that.closest('dd').siblings('dd').find('input');

            if(addressId){
                changeCouponStatus(that,sibs,couponSelE,isChecked);
            }else{
                layer.alert('请选择收货地址！');
                that.prop('checked',false);
            }
        });

        //限时优惠
        discountSelE.on('change',function(){
            var that=$(this);

            if(addressId){
                changeDiscount(that,'e');
            }else{
                layer.alert('请选择收货地址！');
                that.prop('checked',false);
            }
        });
        discountSelC.on('change',function(){
            var that=$(this);

            if(addressId){
                changeDiscount(that,'c');
            }else{
                layer.alert('请选择收货地址！');
                that.prop('checked',false);
            }
        });

        function changeCouponStatus(curInput,siblings,others,isChecked){
            var id=curInput.val();

            others.prop({'disabled':false}).closest('label').removeClass('disabled');

            if(isChecked){
                others.filter('[value="'+id+'"]').prop({'checked':false,'disabled':true}).closest('label').addClass('disabled');
                siblings.prop({'checked':false});
            }

            //发请求
            updatePrice({
                cb: function(res){
                    couponNum.find('.J-val').text(res.total_coupon_price);
                }
            });

        }

        function changeDiscount(curInput,type){
            var isChecked=curInput.prop('checked');
            var sibs=curInput.closest('dd').siblings('dd').find('input');
            var goodsNum=curInput.data('num');
            var id=curInput.val();

            if(isChecked){
                sibs.prop({'checked':false});
            }

            //发请求
            updatePrice({
                discount_type:isChecked?type:'',
                goods_number:isChecked?goodsNum:'',
                cb: function(res){
                    //todo 计算中

                    if(type=='c'){
                        discountSelE.prop('disabled',false);
                        discountSelE.closest('label').toggleClass('disabled',false);
                    }
                    if(type=='e'){
                        discountSelC.prop('disabled',false);
                        discountSelC.closest('label').toggleClass('disabled',false);
                    }
                    if(type=='c'&&!$.isEmptyObject(res.orders.eshopGoods)&&res.orders.eshopGoods.discounts.length){
                        var edis=res.orders.eshopGoods.discounts;
                        var noSel=true;
                        var curDis=discountSelE.filter('[value="'+id+'"]');

                        for(var i=0;i<edis.length;i++){
                            if(edis[i].discount_id==id){
                                noSel=false;
                            }
                        }

                        curDis.prop('disabled',noSel&&curDis.length);
                        curDis.closest('label').toggleClass('disabled',noSel&&curDis.length);

                    }
                    if(type=='e'&&!$.isEmptyObject(res.orders.cshopGoods)&&res.orders.cshopGoods.discounts.length){
                        var cdis=res.orders.cshopGoods.discounts;
                        var noSel=true;
                        var curDis=discountSelC.filter('[value="'+id+'"]');

                        for(var i=0;i<cdis.length;i++){
                            if(cdis[i].discount_id==id){
                                noSel=false;
                            }
                        }


                        curDis.prop('disabled',noSel&&curDis.length);
                        curDis.closest('label').toggleClass('disabled',noSel&&curDis.length);
                    }

                    discountNum.find('.J-val').text(res.total_discount_price);
                }
            });
        }


        function updatePrice(config){

            var couponE=couponSelE.length&&couponSelE.filter(':checked');
            var couponC=couponSelC.length&&couponSelC.filter(':checked');

            var discountE=discountSelE.length&&discountSelE.filter(':checked');
            var discountC=discountSelC.length&&discountSelC.filter(':checked');

            e_coupon_id=couponE.length?couponE.val():'';
            c_coupon_id=couponC.length?couponC.val():'';

            e_discount_id=discountE.length?discountE.val():'';
            c_discount_id=discountC.length?discountC.val():'';

            var opts= $.extend({
                addressId:addressId,
                e_coupon_id:e_coupon_id,
                c_coupon_id:c_coupon_id,
                e_discount_id:e_discount_id,
                c_discount_id:c_discount_id,
                discount_type:'',
                goods_number:'',
                cb: $.noop
            },config,true);

            var url='/order/';

            if(opts.addressId){
                url=url+opts.addressId;

                url=url+'?e_coupon_id='+opts.e_coupon_id;
                url=url+'&c_coupon_id='+opts.c_coupon_id;
                url=url+'&e_discount_id='+opts.e_discount_id;
                url=url+'&c_discount_id='+opts.c_discount_id;

                url=url+'&discount_type='+opts.discount_type;
                url=url+'&goods_number='+opts.goods_number;
            }else{
                layer.alert('请选择收货地址！');
                return false;
            }

            //获取运费信息
            $.ajax({
                url:url,
                type:'put',
                dataType:'json',
                data:{from:'{{$from}}'},
                success:function(res){

                    if(!res.info) return;
                    var data=res.info;

                    var totalOrderPay=$('.js-totalPayPrice'),
                            totalOrderPrice=$('.js-totalOrderPrice'),
                            totalShippingFee=$('.js-totalShippingFee');

                    totalOrderPrice.text('￥'+parseFloat(data.total_order_price).toFixed(2));
                    totalOrderPay.text('￥'+parseFloat(data.total_pay_price).toFixed(2));
                    totalShippingFee.find('.js-num').text( parseFloat(data.total_shipping_fee).toFixed(2));

                    if(!$.isEmptyObject(data.orders.cshopGoods)&&data.orders.cshopGoods.caculator.total_number>0){
                        var curOrder=data.orders.cshopGoods,
                            curOrderItem=$('#cshopOrder'),
                            totalPrice=curOrderItem.find('.js-totalPrice'),
                            numItem=curOrderItem.find('.js-num');

                        totalPrice.text('本单总价：￥'+curOrder.caculator.pay_price);
                        numItem.text(curOrder.caculator.shipping_fee);
                    }
                    if(!$.isEmptyObject(data.orders.eshopGoods)&&data.orders.eshopGoods.caculator.total_number>0){
                        var curOrder=data.orders.eshopGoods,
                            curOrderItem=$('#eshopOrder'),
                            totalPrice=curOrderItem.find('.js-totalPrice'),
                            numItem=curOrderItem.find('.js-num');

                        totalPrice.text('本单总价：￥'+curOrder.caculator.pay_price);
                        numItem.text(curOrder.caculator.shipping_fee);
                    }

                    //回掉
                    typeof opts.cb == 'function' && opts.cb(res.info);

                }
            });
        }

    });
</script>
</body>
</html>